package com.example.treehole.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;

import com.example.treehole.R;
import com.example.treehole.adapter.DynamicCommentAdapter;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.CommentResponse;
import com.example.treehole.entity.DynamicDetailResponse;
import com.example.treehole.utils.ConvertEntityUtils;
import com.example.treehole.viewobject.DynamicComment;
import com.example.treehole.widget.CircleImageView;
import com.google.gson.Gson;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnCreateLottieListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DynamicDetailActivity extends BaseActivity {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_head_line)
    TextView tvHeadLine;
    @BindView(R.id.iv_menu)
    ImageView ivMenu;
    @BindView(R.id.iv_author_header)
    CircleImageView ivAuthorHeader;
    @BindView(R.id.tv_author)
    TextView tvAuthor;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @BindView(R.id.tv_visit_num1)
    TextView tvVisitNum1;
    @BindView(R.id.tv_comment_num1)
    TextView tvCommentNum1;
    @BindView(R.id.tv_start_num1)
    TextView tvStartNum1;
    @BindView(R.id.tv_visit_num2)
    TextView tvVisitNum2;
    @BindView(R.id.tv_comment_num2)
    TextView tvCommentNum2;
    @BindView(R.id.tv_start_num2)
    TextView tvStartNum2;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;

    String publishId;
    CircularProgressDrawable circularProgressDrawable;

    DynamicDetailResponse.DataDTO data;
    List<DynamicComment> commentData;
    DynamicCommentAdapter adapter=new DynamicCommentAdapter(this);
    int commentNumber = 1;
    PopupWindow popupWindow;
    EditText editText;
    TextView  tvPublish;
    LoadingDialog loadingDialog;
    boolean isStar=false;


    @Override
    protected int initLayout() {
        return R.layout.activity_dynamic_detail;
    }

    @Override
    protected void initData() {
        tvHeadLine.setText("动态");

        //获取数据
        publishId = getIntent().getStringExtra("id");
        boolean b=getIntent().getBooleanExtra("isMine",false);
        //如果是自己的动态，右上角添加菜单
        if (b){
            ivMenu.setVisibility(View.VISIBLE);
        }

        //加载数据
        loadData();

        //回复弹出框准备
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.popup_dynamic_reply, null);
        editText = layout.findViewById(R.id.et_reply);
        tvPublish=layout.findViewById(R.id.tv_publish);
        popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        //刷新全部刷新，加载只加载评论
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                commentNumber = 1;
                loadData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                commentNumber++;
                loadComments(false);
            }
        });
        //加载框初始化
        loadingDialog=new LoadingDialog(this);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length()==0)
                    tvPublish.setTextColor(Color.GRAY);
                else
                    tvPublish.setTextColor(Color.BLACK);
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        tvPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().toString().length()==0)
                    return;
                publishComment(editText.getText().toString());
            }
        });
    }

    private void publishComment(String msg) {
        HashMap<String,String> mParams=new HashMap<>();
        mParams.put("userId",getStringFromSp("id"));
        mParams.put("publishId",publishId);
        mParams.put("text",msg);
        loadingDialog.setLoadingText("发布中").show();
        Api.config(ApiConfig.POST_DYNAMIC_COMMENT,mParams).postRequest(this, new Callback() {
            @Override
            public void onSuccess(String res) {
                if (res.contains("200")){
                    runOnUiThread(new Runnable() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void run() {
                            popupWindow.dismiss();
                            long num=Long.parseLong(tvCommentNum1.getText().toString());
                            tvCommentNum1.setText(num+1+"");
                            tvCommentNum2.setText(num+1+"");
                            loadingDialog.close();
                        }
                    });
                    commentNumber=1;
                    loadComments(true);
                }
            }
            @Override
            public void onFailure(Exception e) {
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    private void loadData() {
        //获取动态详情
        String url = ApiConfig.GET_DYNAMIC_DETAIL + "/" + publishId;
        Api.config(url, new HashMap<>()).getRequest(this, new Callback() {
            @Override
            public void onSuccess(String res) {
                refreshLayout.finishRefresh(true);
                DynamicDetailResponse dynamicDetailResponse = new Gson().fromJson(res, DynamicDetailResponse.class);
                String code = dynamicDetailResponse.getCode();
                if (code.equals("200")) {
                    DynamicDetailResponse.DataDTO dataDTOS = dynamicDetailResponse.getData();
                    if (dataDTOS != null) {
                        data = dataDTOS;
                        mHandler.sendEmptyMessage(1);
                    } else {
                        showToastSync(getString(R.string.dynamic_not_exist));
                    }
                } else {
                    showToastSync(dynamicDetailResponse.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                refreshLayout.finishRefresh(true);
                showToastSync(getString(R.string.check_network));
            }
        });
        //获取评论,初始化进来默认刷新
        loadComments(true);
    }

    private void loadComments(boolean isFresh) {
        String url = ApiConfig.GET_DYNAMIC_COMMENT;
        HashMap<String,String> mParams=new HashMap<>();
        mParams.put("publishId",publishId);
        mParams.put("page",commentNumber+"");
        Api.config(url,mParams ).getRequest(this, new Callback() {
            @Override
            public void onSuccess(String res) {
                if (isFresh)
                    refreshLayout.finishRefresh(true);
                else
                    refreshLayout.finishLoadMore(true);
                CommentResponse commentResponse = new Gson().fromJson(res, CommentResponse.class);
                String code = commentResponse.getCode();
                if (code.equals("200")) {
                    List<CommentResponse.DataDTO> dataDTOS = commentResponse.getData();
                    if (dataDTOS != null) {
                        List<DynamicComment> newData = ConvertEntityUtils.convertToDynamicComment(DynamicDetailActivity.this,dataDTOS);
                        if (isFresh)
                            commentData = newData;
                        else
                            commentData.addAll(newData);
                        mHandler.sendEmptyMessage(2);
                    } else {
                        showToastSync(getString(R.string.dynamic_not_exist));
                    }
                } else {
                    showToastSync(commentResponse.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                refreshLayout.finishRefresh(true);
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                showDetail();
            } else if (msg.what == 2) {
                showComments();
            }else if (msg.what==3){
                loadingDialog.close();
            }
        }
    };

    @SuppressLint("NotifyDataSetChanged")
    private void showComments() {
        LinearLayoutManager manager=new LinearLayoutManager(this);
        rvComment.setLayoutManager(manager);
        rvComment.setAdapter(adapter);
        adapter.setData(commentData);
        adapter.notifyDataSetChanged();
    }

    private void showDetail() {
        try {
            Picasso.get().load(data.getDynamicEntity().getUser().getHeadUrl()).into(ivAuthorHeader);
            tvAuthor.setText(data.getDynamicEntity().getUser().getName());
            tvTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(data.getDynamicEntity().getModifyTime()));
            if (data.getDynamicEntity().getTitle()!=null && !data.getDynamicEntity().getTitle().equals(""))
                tvTitle.setText(data.getDynamicEntity().getTitle());
            else
                tvTitle.setVisibility(View.GONE);
            tvContent.setText(data.getDynamicEntity().getText());
            tvVisitNum1.setText(String.valueOf(data.getDynamicEntity().getVisits()));
            tvVisitNum2.setText(String.valueOf(data.getDynamicEntity().getVisits()));
            tvCommentNum1.setText(String.valueOf(data.getDynamicEntity().getCommentsNumber()));
            tvCommentNum2.setText(String.valueOf(data.getDynamicEntity().getCommentsNumber()));
            tvStartNum1.setText(String.valueOf(data.getDynamicEntity().getStar()));
            tvStartNum2.setText(String.valueOf(data.getDynamicEntity().getStar()));
            showImage();
        }catch(Exception e){
            e.printStackTrace();
            showToast(getString(R.string.load_error));
        }
    }

    private void showImage() {
        List<String> images = data.getImagesUrl();
        if (images != null) {
            //图片加载
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
            if (images.size() == 1)
                gridLayoutManager.setSpanCount(1);
            if (images.size() == 4 || images.size() == 2)
                gridLayoutManager.setSpanCount(2);
            rvImg.setLayoutManager(gridLayoutManager);
            rvImg.setAdapter(new RecyclerView.Adapter() {
                @NonNull
                @Override
                public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dynamic_img, parent, false);
                    return new ViewHolder(view);
                }

                @Override
                public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
                    ImageView iv = holder.itemView.findViewById(R.id.iv);

                    /*imageView设置了adjustViewBounds,即保存了图片本先的比例
                        这里根据情况分两种，如果只有一张图片，则让图片直接伸张，不做限制；(但是为了图片太长，这里居中显示centerCrop)
                                              如果多张照片，考虑到每张图片的高宽比例不同，但是为了要整齐，统一将图片进行裁减，
                                              这里用resize，两个参数保持一致，但是具体大小，没太弄明白,默认400效果还不错。

                     */
                    RequestCreator requestCreator = Picasso.get()
                            .load(images.get(position));

                    if (images.size() == 1)
                        requestCreator.fit().centerCrop();
                    else
                        requestCreator.resize(600, 600).centerCrop();

                    //设置加载动画
                    circularProgressDrawable = new CircularProgressDrawable(rvImg.getContext());
                    circularProgressDrawable.setStrokeWidth(10f);
                    circularProgressDrawable.setColorSchemeColors(getResources().getColor(R.color.blue));
                    circularProgressDrawable.setCenterRadius(30f);
                    circularProgressDrawable.start();
                    requestCreator
                            .placeholder(circularProgressDrawable)
                            .error(R.mipmap.tree_hole)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            jumpTo(getString(R.string.URL), images, position);
                        }
                    });
                }

                @Override
                public int getItemCount() {
                    return images.size();
                }

                class ViewHolder extends RecyclerView.ViewHolder {
                    ImageView iv;

                    public ViewHolder(View view) {
                        super(view);
                        iv = findViewById(R.id.iv);
                    }
                }
            });
        }
    }


    private void showPopupWindow() {
        //显出布局
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        //弹窗消失监听事件
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public void showKeyBoard(EditText editText) {
        // 获取编辑框焦点
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //打开软键盘
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.iv_exit, R.id.iv_author_header, R.id.tv_author, R.id.tv_time, R.id.tv_visit_num1,R.id.iv_menu,
            R.id.tv_comment_num1, R.id.tv_start_num1, R.id.btn_reply, R.id.tv_visit_num2, R.id.tv_comment_num2, R.id.tv_start_num2,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_menu:
                showPopupMenu();
                break;
            case R.id.iv_exit:
                finish();
                break;
            case R.id.iv_author_header:
            case R.id.tv_author:
            case R.id.tv_time:
                //进入主页
                break;
            case R.id.tv_start_num1:
            case R.id.tv_start_num2:
                star();
                break;
            case R.id.btn_reply:
            case R.id.tv_comment_num1:
            case R.id.tv_comment_num2:
                showPopupWindow();
                setBackgroundAlpha(0.7f);
                showKeyBoard(editText);
                break;
        }
    }

    @SuppressLint("Range")
    private void showPopupMenu() {
        //menu准备
        PopupMenu popupMenu = new PopupMenu(this, ivMenu);
        popupMenu.getMenuInflater().inflate(R.menu.my_dynamic_detail, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                //对话框准备
                CircleDialog.Builder builder = new CircleDialog.Builder();
                builder.setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        builder.dismiss();
                    }
                }).setWidth(800f);
                //判断
                if (item.getItemId()==R.id.delete){
                    builder.setTitle("要删除这条动态吗？")
                            .setPositive("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    loadingDialog.setLoadingText("处理中").show();
                                    HashMap<String,String> mParams=new HashMap<>();
                                    mParams.put("publishId",publishId);
                                    mParams.put("userId",getStringFromSp("id"));
                                    Api.config(ApiConfig.DYNAMIC_DELETE,mParams).postRequest(DynamicDetailActivity.this, new Callback() {
                                        @Override
                                        public void onSuccess(String res) {
                                            mHandler.sendEmptyMessage(3);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (res.contains("200")){
                                                        showToast("删除成功");
                                                        setResult(200);
                                                        finishAndRemoveTask();
                                                    }else{
                                                        showToast("删除失败");
                                                    }
                                                }
                                            });
                                        }
                                        @Override
                                        public void onFailure(Exception e) {
                                            mHandler.sendEmptyMessage(3);
                                            showToastSync(getString(R.string.check_network));
                                        }
                                    });
                                }
                            });
                }else {
                    builder.setTitle("要修改属性吗？")
                            .setPositive("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    showToast("我知道了");
                                }
                            });
                }
                builder.show(getSupportFragmentManager());
                return false;
            }
        });
        popupMenu.show();
    }



    @SuppressLint("SetTextI18n")
    private void star() {
        String url="";
        if (!isStar){
            url=ApiConfig.DYNAMIC_STAR;
            long num=Long.parseLong(tvStartNum1.getText().toString());
            tvStartNum1.setText(num+1+"");
            tvStartNum2.setText(num+1+"");
            Drawable drawable= getResources().getDrawable(R.mipmap.star_light);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvStartNum1.setCompoundDrawables(drawable,null,null,null);
            tvStartNum1.setTextColor(getResources().getColor(R.color.blue));
            tvStartNum2.setCompoundDrawables(drawable,null,null,null);
            tvStartNum2.setTextColor(getResources().getColor(R.color.blue));
        }else{
            url=ApiConfig.DYNAMIC_NO_STAR;
            long num=Long.parseLong(tvStartNum1.getText().toString());
            tvStartNum1.setText(num-1+"");
            tvStartNum2.setText(num-1+"");
            Drawable drawable= getResources().getDrawable(R.mipmap.star);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvStartNum1.setCompoundDrawables(drawable,null,null,null);
            tvStartNum1.setTextColor(Color.GRAY);
            tvStartNum2.setCompoundDrawables(drawable,null,null,null);
            tvStartNum2.setTextColor(Color.GRAY);
        }
        isStar=!isStar;
        HashMap<String,String> mParams=new HashMap<>();
        Api.config(url,mParams).getRequest(this, new Callback() {
            @Override
            public void onSuccess(String res) {
            }
            @Override
            public void onFailure(Exception e) {
            }
        });
    }
}